import { useReducer } from "react"

const reducer=(state,action)=>{
    switch(action.type){
        case'add':
        return [...state,action.payload]
        case 'remove':
        return state.filter((_,i)=>i!==action.payload)
        case'clear':
        return []
        default:
            return state
    }
}

const ListReducerDemo=()=>{
    const [state,dispath]=useReducer(reducer,['1','2','3','4'])

    console.log(state)
    return(<>
    <button onClick={()=>{dispath({type:'add',payload:Math.random()})}}> 添加</button>

    <button onClick={()=>{dispath({type:'clear'})}}> 清楚</button>
         <ul>
             {state.map((item,index)=>(<li  onClick={()=>{dispath({type:'remove',payload:index})}}  key={index}>{item}</li>))}
             <li></li>
         </ul>




    </>)
}

console.log(reducer([],{type:'add',text:'a'}))
console.log(reducer(['a','b','c','d'],{type:'remove',payload:1}))

export default ListReducerDemo